package com.example.xd.Util;

import com.example.xd.Entity.Video;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Service
public class VideoDurationUtil {

    public static double getVideoDuration(String videoPath) {
        try {
            // 构建FFmpeg命令，用于获取视频时长
            String[] command = {
                    "ffmpeg",
                    "-i",
                    videoPath,
                    "-map",
                    "0:v:0",
                    "-c",
                    "copy",
                    "-f",
                    "null",
                    "-"
            };

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();

            // 读取命令执行的错误输出流，从中提取视频时长信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            while ((line = reader.readLine())!= null) {
                if (line.contains("time=")) {
                    // 从包含"time="的行中提取出时间字符串，格式"time=00:00:00.00"，然后解析出时长秒数
                    String timeStr = line.substring(line.indexOf("time=") + 5, line.indexOf("time=") + 13);
                    String[] parts = timeStr.split(":");
                    int hours = Integer.parseInt(parts[0]);
                    int minutes = Integer.parseInt(parts[1]);
                    double seconds = Double.parseDouble(parts[2]);
                    return hours * 3600 + minutes * 60 + seconds;
                }
            }

            // 如果没有成功获取到时长信息，返回默认时长0
            return 0.0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0.0;
        }
    }
}
//@Service
//public class VideoDurationUtil {
//
//    public double getVideoDuration(String videoPath) {
//        try {
//            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoPath);
//            grabber.start();
//            double fps = grabber.getFrameRate();
//            long firmCount = grabber.getLengthInFrames();
//            double videoDuration = (double) firmCount / fps;
//            grabber.stop();
//            return videoDuration;
//        } catch (FrameGrabber.Exception e) {
//            e.printStackTrace();
//        }
//        return 0.0;
//    }
//}

